﻿#include "http.h"
#include <QTimer>

http::http(QObject *parent) : QObject(parent)
{

}

void http::Get(QUrl u, QString filename)
{
    QEventLoop loop;
    QNetworkRequest request;
    //QNetworkAccessManager * m = new QNetworkAccessManager(this);
    url = u;
    request.setUrl(QUrl(QString("http://www.ceic.ac.cn/ajax/speedsearch?num=2&&page=1&&callback=jQuery18009019735196669112_1652777947869&_=1652777983103")));

    /*if (reply!=Q_NULLPTR)
    {
        reply->deleteLater();
    }*/
    //connect(m,&QNetworkAccessManager::finished,this,&http::replyFinished);

    reply = manger.get(request);
    connect(reply,SIGNAL(finished()),&loop,SLOT(quit()));
    loop.exec();//开启事件循环
    qDebug()<<"endl";
    /*QTimer opt;
    opt.start(600);

    if(opt.isActive())
    {
        opt.stop();
        qDebug()<<"空额是";

        if(reply->error() > 0)
        {
            qDebug()<<"查询错误";
        }
    }
    else
    {
        loop.quit();
        qDebug()<<"结束了";
    }*/

    QByteArray bytes = reply->readAll();
    const QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
    reply-> deleteLater();
    reply = Q_NULLPTR;
    if(!redirectionTarget.isNull()){
        const QUrl redirectedUrl = url.resolved(redirectionTarget.toUrl());
        qDebug() << "redirectedUrl:"<<redirectedUrl.url();
        Get(redirectedUrl,filename);
        return;
    }
    html_text = bytes;
    QString urlname = url.url();
    qDebug()<<"Succeed";
    qDebug()<<urlname;
    QFile file(filename);
    file.open(QFile::WriteOnly);
    file.write(bytes);
    file.close();
}
void http::replyFinished(QNetworkReply *reply)
{
    qDebug()<<"finished"<<endl;
}

void http::Save(QUrl u, QString filename)
{
    QEventLoop loop;
    QNetworkRequest request;
    QNetworkAccessManager * m = new QNetworkAccessManager(this);
    url = u;
    request.setUrl(QUrl(QString("http://www.ceic.ac.cn/ajax/speedsearch?num=1&&page=1&&callback=jQuery18007232534314640713_1652862832970&_=1652869037554")));


    /*QTimer timer;
    timer.setSingleShot(true);

    //connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));*/

    //connect(reply,&QNetworkReply::finished,loop,&QEventLoop::quit);
    reply = m->get(request);
    loop.exec();
    //todo

    QString urlname = url.url();
    qDebug()<<"Succeed";
    qDebug()<<urlname;

    QByteArray bytes = reply->readAll();
    qDebug()<<bytes;
    QFile file(filename);
    file.open(QFile::WriteOnly);
    file.write(bytes);
    file.close();
}

